package org.example.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;

public class ALiYunOssUtils {

    private static String accessKeyId = "LTAI5tHWGSZJsN3usJURFka2";
    private static String accessKeySecret = "oZvcBtVST2QaIW8MvX7dxDYImMAmu4";
    private static String endpoint = "https://oss-cn-guangzhou.aliyuncs.com";
    private static String bucketName = "java-luntan";

    //上传文件
    public List<String> uploadFile(int userId, String userName, String content) {

        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        StringBuilder objectName = new StringBuilder(userId + "-" + userName + "/");

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // UUID 避免文件覆盖
//        objectName =objectName+ UUID.randomUUID().toString()+".txt";
        objectName.append(UUID.randomUUID().toString()).append(".txt");

        // 填写字符串。
//        content = "Hello OSS，你好世界";

        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName.toString(), new ByteArrayInputStream(content.getBytes()));

        // 上传字符串。
        PutObjectResult result = ossClient.putObject(putObjectRequest);
        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
//        System.out.println(url);
        //关闭 链接
        ossClient.shutdown();
        List<String> ls = new ArrayList();
        ls.add(url);
        ls.add(objectName.toString());
        return ls;
    }

    //下载文件
    public String downloadFile(String url, String objectName) {

        // 填写不包含Bucket名称在内的Object完整路径，例如testfolder/exampleobject.txt。
//         objectName = "1-张三af5202d6-6fb6-4e68-89aa-81bafa9ada8d.txt";
        // 填写Object下载到本地的完整路径。
//        File file1 = new File("src\\main\\resources\\temp.txt");
        StringBuilder obj = new StringBuilder("src\\main\\resources\\");
        obj.append(objectName);

        File file = new File(obj.toString());
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        ossClient.getObject(new GetObjectRequest(bucketName, objectName), file);

        ossClient.shutdown();
//        System.out.println("下载成功");
        return obj.toString();
    }
}
